package com.flutter_ecg.flutter_ecg.ecgapplication.ecgrealtimecheck;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.ikinloop.iklibecgcheck.IKEcgCheck;
import com.flutter_ecg.flutter_ecg.R;
import com.flutter_ecg.flutter_ecg.ecgapplication.utils.Constants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/*
    该页面类实现了心电图分析结果的显示。
   */
public class EcgResultActivity extends AppCompatActivity {

    private final String TAG = "EcgResultActivity:::";

    private RelativeLayout resultBackLayout;
    private ImageView backImageView;
    private IKEcgResultLayout ikEcgResultLayout;
    private String detectTime;

    public static final String ECG = "ecg";
    public static String SDCARD = Environment.getExternalStorageDirectory().getPath();
    private static final String ECG_FILEPATH_DEFAULT = SDCARD.endsWith(File.separator) ? SDCARD + ECG : SDCARD
            + File.separator + ECG;
    private static String ECG_FILEPATH = Constants.ecgDataPath;
    private String tarFilePath;

    private IKEcgCheck ikEcgCheck;

    private boolean isScreenland = false;
    private int[] ecgData;
    private int[] ecgEcgState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ecg_result);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        detectTime = sdf.format(new Date(Long.parseLong(String.valueOf(System.currentTimeMillis()))));

        resultBackLayout = (RelativeLayout) findViewById(R.id.resultBackLayout);
        backImageView = (ImageView) findViewById(R.id.resultBack);
        backImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ikEcgResultLayout = (IKEcgResultLayout) findViewById(R.id.result_layout);
        ikEcgResultLayout.initEcgResultLayout();
        ikEcgResultLayout.getFullScreenIv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setScreenOritation();
            }
        });

        initIKEcgLib();
        initUnpackPath();
        initEcgData();

        initResultData();
    }

    /**
     * Initialization IKLibrary
     */
    private void initIKEcgLib() {
        if (null == ikEcgCheck) {
            ikEcgCheck = IKEcgCheck.getInstance(EcgResultActivity.this);
        }
    }

    private void initUnpackPath() {
        tarFilePath = ikEcgCheck.IKGetCurrEcgDataFilePath();
        if (TextUtils.isEmpty(tarFilePath)) {
            File file = new File(ECG_FILEPATH);
            if (!file.exists()) {
                file = new File(ECG_FILEPATH_DEFAULT);
            }
            if (TextUtils.isEmpty(tarFilePath) && file.exists()) {
                File[] files = file.listFiles();
                for (File file1 : files) {
                    if (file1.getAbsolutePath().contains(".tar")) {
                        tarFilePath = file1.getAbsolutePath();
//                        Log.i("setData:::", "unpackPath::" + tarFilePath);
                        break;
                    }
                }
            }
        }
    }

    private void initEcgData() {
        if (!tarFilePath.endsWith(".tar")) {
            return;
        }
        //ecgFileDirPath is the unpack dir path of tar
        String ecgFileDirPath = tarFilePath.substring(0, tarFilePath.length() - 4);
        File ecgFileDir = new File(ecgFileDirPath);
        int ecgDataLength = 0;
        if (!ecgFileDir.exists()) {
            ecgDataLength = ikEcgCheck.IKUnPackEcgDataFile(tarFilePath, ecgData);
        } else {
            ecgDataLength = ikEcgCheck.IKEcgAnalyzeSdkGetEcgDataLength(ecgFileDirPath);
        }
        if (ecgDataLength <= 0) {
            return;
        }
        ecgData = new int[ecgDataLength];
        ecgEcgState = new int[ecgDataLength];
        ikEcgCheck.IKecgAnalyzeSdkGetEcgDataFromFile(ecgFileDirPath, ecgDataLength, ecgData, ecgEcgState);
        ikEcgResultLayout.setEcgData(ecgData, ecgEcgState);
    }

    private void initResultData() {
        Intent intent = getIntent();
        String ecgSmartResult = intent.getStringExtra(Constants.ECGRESMARTSULT_KEY);

        ikEcgResultLayout.setDetectTime(detectTime);
        ikEcgResultLayout.setDuration(40);

        if (TextUtils.isEmpty(ecgSmartResult)) {
            return;
        }

        JSONArray ecgSympJsonArray = null;
        JSONObject ecgValObj = null;
        try {
            JSONObject ecgSmartResultObj = new JSONObject(ecgSmartResult);
            ecgSympJsonArray = ecgSmartResultObj.getJSONArray("ecgsymps");//获取数组
            ecgValObj = ecgSmartResultObj.getJSONObject("ecgval");
            Log.i(TAG, ecgValObj.getString("breath"));
            Log.i(TAG, ecgValObj.getString("hrmean"));
            ikEcgResultLayout.setHrValue(ecgValObj.getString("hrmean"));
            ikEcgResultLayout.setBreathValue(ecgValObj.getString("breath"));
            ikEcgResultLayout.setPressureValue(ecgValObj.getString("pressure"));

            List<String> suggestionList = new ArrayList<>();
            List<String> sympNameList = new ArrayList<>();
            for (int i = 0; i < ecgSympJsonArray.length(); i++) {
                Log.i(TAG, i + ":::" + ecgSympJsonArray.get(i).toString());
                JSONObject ecgSympObj = ecgSympJsonArray.getJSONObject(i);
                suggestionList.add(ecgSympObj.getString("suggestion"));
                sympNameList.add(ecgSympObj.getString("name"));
            }
            ikEcgResultLayout.setAnalyzeResult(sympNameList);
            ikEcgResultLayout.setSuggest(suggestionList);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置屏幕的横竖屏
     */
    private void setScreenOritation() {
        if (isScreenland) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            isScreenland = true;
            resultBackLayout.setVisibility(View.GONE);
        } else {
            isScreenland = false;
            resultBackLayout.setVisibility(View.VISIBLE);
        }
        ikEcgResultLayout.onConfigureChanged(newConfig.orientation);
    }
}
